import { call, put, fork, select, take } from 'redux-saga/effects'
import { message } from 'antd'
import actions, { GET_VALIDATE_PICTURE, LOGIN } from '@/actions/login'
import api from '@/api/login'
import util from '@/utils'
import { history } from '@/route/history'

export function* getValidatePicture() { 

  try {
    const { data } = yield call(api.getValidatePicture)
    const validatePictureData = util.transformBufferToBase64(data)
    yield put(actions.setValidatePicture(validatePictureData))
  } catch (error) {
    console.log('error', error)
    yield put(actions.getValidatePictureFail())
  }
}

export function* login() {
  const params = yield select(({ loginReducer: { account, passWord, validateCode } }) => ({
     account,
    password: passWord,
    code: validateCode
  }))
  const formdata = new FormData()
  formdata.append('account', params.account)
  formdata.append('password', params.password)
  formdata.append('code', params.code)
  try {
    const { isSuccess, desc } = yield call(api.login, formdata)
    if (isSuccess) {
      yield put(actions.loginSuccess())
      history.push('/index')
    } else {
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.loginFail())
    message.error(error.message || '登录错误')
    yield call(getValidatePicture)
  }
}

export function* watchLogin() {
  while (true) {
    yield take(LOGIN)
    yield call(login)
  }
}

export function* watchGetValidatePicture() {
  while (true) {
    yield take(GET_VALIDATE_PICTURE)
    yield call(getValidatePicture)
  }
}

export default [
  fork(watchGetValidatePicture),
  fork(watchLogin)
]